package io.renren.modules.generator.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;

import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.generator.entity.BsnMentorEntity;
import io.renren.modules.generator.service.BsnMentorService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.common.utils.Constant;
import io.renren.common.utils.ConstantLocal;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.ShortUuidUtils;



/**
 * 导师表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-05-30 11:06:00
 */
@RestController
@RequestMapping("generator/bsnmentor")
public class BsnMentorController extends AbstractController {
    @Autowired
    private BsnMentorService bsnMentorService;

    @Autowired
    private SysUserService sysUserService;
    
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> params){
    	params.put("sidx", "createTime");
    	params.put("order", "desc");
        PageUtils page = bsnMentorService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id){
		BsnMentorEntity bsnMentor = bsnMentorService.selectById(id);
        return R.ok().put("bsnMentor", bsnMentor);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody BsnMentorEntity bsnMentor){
    	R r = this.validate(bsnMentor);
    	if (!r.isOk()) {
    		return r;
    	}
    	
    	//校验手机号是否被占用
    	if (sysUserService.mobileExist(bsnMentor.getShouji())) {
    		return R.error(ConstantLocal.ERROR_IS_EXIST, "手机号已被其他用户占用，请变更手机号！");
    	}
    	
    	bsnMentor.setId(ShortUuidUtils.generateShortUuid());
    	bsnMentor.setCreateTime(new Date());
		bsnMentorService.insert(bsnMentor);

        return R.ok().put("bsnMentor", bsnMentor);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BsnMentorEntity bsnMentor){
    	R r = this.validate(bsnMentor);
    	if (!r.isOk()) {
    		return r;
    	}
    	//校验手机号是否被占用
    	if (StringUtils.isBlank(bsnMentor.getLoginId())) {
        	//校验手机号是否被占用
        	if (sysUserService.mobileExist(bsnMentor.getShouji())) {
        		return R.error(ConstantLocal.ERROR_IS_EXIST, "手机号已被其他用户占用，请变更手机号！");
        	}
    	} else {
    		if (!sysUserService.mobileIsOnesOwn(bsnMentor.getShouji(), bsnMentor.getLoginId())) {
    			return R.error(ConstantLocal.ERROR_IS_EXIST, "手机号已被其他用户占用，请变更手机号！");
    		}
    	}
    	
		bsnMentorService.updateById(bsnMentor);
		//判断登录用户是否需要更新手机号
		SysUserEntity user = sysUserService.selectById(bsnMentor.getLoginId());
		if (user == null) {
			return R.ok();	
		}
		if (!user.getMobile().equals(bsnMentor.getShouji())) {
			user.setMobile(bsnMentor.getShouji());
			sysUserService.update(user);
		}
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody String[] ids){
			bsnMentorService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 修改登录id
     */
    @RequestMapping("/updateLoginId")
    public R updateLoginId(@RequestBody Map<String, Object> params){
    	BsnMentorEntity entity = new BsnMentorEntity();
    	String loginId = params.get("loginId").toString();
    	String mentorId = params.get("id").toString();
    	
    	entity.setLoginId(loginId);
		bsnMentorService.update(entity, 
				new EntityWrapper<BsnMentorEntity>().eq("id", mentorId));
        return R.ok();
    }
    
    /**
     * 根据登录用户信息查找信息
     */
    @Login
    @RequestMapping("/infoBylogin")
    public R infoBylogin(@LoginUser SysUserEntity loginUser){
    	String loginId = "8"; //测试使用
    	if (loginUser == null) {
//    		return R.ok();
    	} else {
    		loginId = loginUser.getUserId().toString();
    	}
		BsnMentorEntity bsnMentor = bsnMentorService.selectByLoginId(loginId);
        return R.ok().put("bsnMentor", bsnMentor);
    }
    
    /**
     * 根据登录用户信息查找信息
     */
    @RequestMapping("/managerInfo")
    public R managerInfo(){
    	SysUserEntity user = new SysUserEntity();
    	user.setUserType(Constant.SysUserType.MANAGER.getValue());
    	EntityWrapper<SysUserEntity> wrapper = new EntityWrapper<SysUserEntity>(user);
    	user = sysUserService.selectOne(wrapper);
    	SysUserEntity retUser = new SysUserEntity();
    	retUser.setUsername(user.getUsername());
    	retUser.setEmail(user.getEmail());
    	retUser.setMobile(user.getMobile());
    	retUser.setUserType(user.getUserType());
        return R.ok().put("bsnManager", retUser);
    }
    /**
     * 信息校验
     * @param bsnMentor
     * @param r
     * @return
     */
    private R validate(BsnMentorEntity bsnMentor) {
    	if (StringUtils.isBlank(bsnMentor.getXingm())) {
    		return R.error(ConstantLocal.ERROR_NOT_BLANK, "姓名不能为空");
    	}
    	
    	if (StringUtils.isBlank(bsnMentor.getShouji())) {
    		return R.error(ConstantLocal.ERROR_NOT_BLANK, "手机号不能为空");
    	}
    	
    	return R.ok();
    }
}
